#!/usr/bin/env bash
# gitold — checkout the version of a file from N units ago as a new file.
# Usage: gitold <file> <count>[d|h|w|m]

set -e

usage() {
    cat <<EOF
Usage: gitold <file> <count>[d|h|w|m]
  d  days
  h  hours
  w  weeks
  m  months
Example: gitold src/foo.c 3d    -> foo.3d.c
EOF
    exit 1
}

[[ $# -eq 2 ]] || usage

FILE=$1
shift
SPEC=$1

# 解析时间描述
if [[ ! "$SPEC" =~ ^([0-9]+)([dhwm])$ ]]; then
    usage
fi

COUNT=${BASH_REMATCH[1]}
UNIT=${BASH_REMATCH[2]}

case "$UNIT" in
    d)  DATE_SPEC="${COUNT} days ago" ;;
    h)  DATE_SPEC="${COUNT} hours ago" ;;
    w)  DATE_SPEC="${COUNT} weeks ago" ;;
    m)  DATE_SPEC="${COUNT} months ago" ;;
    *)  usage ;;
esac

# 找到那次提交
COMMIT=$(git rev-list -n1 --before="$DATE_SPEC" HEAD -- "$FILE") || {
    echo "Error: cannot find commit for $FILE before $DATE_SPEC"
    exit 1
}

# 构建输出文件名
BASE=$(basename "$FILE")
EXT="${BASE##*.}"
NAME="${BASE%.*}"
OUT="${NAME}.${SPEC}.${EXT}"

# 检出内容
git show "$COMMIT:$FILE" > "$OUT"
echo "Created $OUT (from commit $COMMIT)"
